#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

//    addCookieHeader(QUrl("http://localhost:51671/account/login"));
//    get(QUrl("http://localhost:51671/account/isLogin"));
    post(QUrl("http://localhost:51671/account/login"), QByteArray("account=admin&password=123456"));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::get(const QUrl url)
{
    //request 设置 url
    QNetworkRequest t_networkRequest(url);

    //request 设置cookie
    QVariant var;
    var.setValue(m_listCookie);
    t_networkRequest.setHeader(QNetworkRequest::CookieHeader, var);

    //get
    QNetworkReply *reply = m_networkAccessManager.get(t_networkRequest);

    //设置回调
    connect(reply, &QIODevice::readyRead, this, [this, reply](){qDebug() << reply->readAll();});
    connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
            this, [](){});
    connect(reply, &QNetworkReply::sslErrors,
            this, [](const QList<QSslError> &errors){qDebug() << errors;});
}

void MainWindow::post(QUrl url, QByteArray byte)
{
    //request 设置 url
    QNetworkRequest t_networkRequest(url);

    //head 设置cookie
    QVariant var;
    var.setValue(m_listCookie);
    t_networkRequest.setHeader(QNetworkRequest::CookieHeader,var);

    //post
    QNetworkReply *t_networkReply= m_networkAccessManager.post(t_networkRequest, byte);

    //请求完成连接信号槽
    connect(t_networkReply,&QNetworkReply::finished,this,[this, url](){
        QNetworkCookieJar * jar= m_networkAccessManager.cookieJar();
        m_listCookie= jar->cookiesForUrl(url);
        for(int i=0;i<m_listCookie.length();i++)
        {
             qDebug()<<m_listCookie[i].name()<<":"<<m_listCookie[i].value();
        }
        get(QUrl("http://localhost:51671/account/isLogin"));
    });
}
